import { login as apiLogin } from "@/api/user";

const state = {
  token: localStorage.getItem("token") || "",
  userInfo: JSON.parse(localStorage.getItem("userInfo")) || {},
};

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token;
    localStorage.setItem("token", token);
  },
  SET_USER(state, userInfo) {
    state.userInfo = userInfo;
    localStorage.setItem("userInfo", JSON.stringify(userInfo));
  },
  CLEAR_USER(state) {
    state.token = "";
    state.userInfo = {};
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo");
  },
};

const actions = {
  // 登录
  login({ commit }, loginData) {
    return new Promise((resolve, reject) => {
      apiLogin(loginData)
        .then((response) => {
          const { code, msg, data } = response;
          if (code === 200 && data) {
            commit("SET_TOKEN", data.token);
            commit("SET_USER", data.user);
            resolve(data);
          } else {
            reject(new Error(msg || "登录失败，请检查用户名和密码"));
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 退出登录
  logout({ commit }) {
    return new Promise((resolve) => {
      commit("CLEAR_USER");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
